<template>
  <div class="mains">
    <div style="min-height: 915px; padding: 100px 0 0 600px">
      <div class="login_box">
        <p class="login_title">
          <span class="login-logo" style="clear:both">健 康 书 院 管 理 系 统</span>
          <br>
          <br>
          <span
            :class="isActiveIndex === 0 ? 'isActiveTitle' : ''"
            @click="accountLogin"
            >账号登录</span
          ><!-- 利用三元运算符判定点击了哪个登录,从而绑定样式 -->
          <span
            :class="isActiveIndex === 1 ? 'isActiveTitle' : ''"
            @click="smsLogin"
            >微信登录</span
          >
        </p>
        <el-form
          v-if="isActive"
          ref="loginForm"
          :rules="loginRules"
          :model="loginForm"
          label-width="80px"
        >
          <el-form-item label="账号：" prop="username">
            <el-input
              ref="username"
              v-model="loginForm.username"
              placeholder="Username"
              name="username"
              type="text"
            />
          </el-form-item>
          <el-form-item label="密码：" prop="password">
            <el-input
              :key="passwordType"
              ref="password"
              v-model="loginForm.password"
              :type="passwordType"
              placeholder="Password"
              name="password"
              @keyup.enter.native="handleLogin"
              show-password
            />
          </el-form-item>

          <el-button
            class="login_btn"
            :loading="loading"
            @click.native.prevent="handleLogin"
            >立 即 登 录</el-button
          >
          <el-form-item
            label="提示"
            style="font-size: 15px; margin-top: 10px; margin-left: 70px"
            >username: test</el-form-item
          >
          <el-form-item label="" style="margin-top: -30px"
            >password: 123456</el-form-item
          >
          <!-- <div class="tips">
        <span >提示：username: admin</span>
        <div class="bottom">
          <span > password: 123321</span>
        </div>
          </div> -->

          <!-- <span> 如需账号，密码请联系管理员！</span> -->
        </el-form>
        <!-- 用微信登录 -->
        <el-form v-else ref="loginForm2" :model="loginForm2" label-width="80px">
          <div id="weixinLogin">
            <!-- <img class="qrcode" :src="qrcodes" alt=""> -->
          </div>

          <!-- <img class="qrcode" src="https://open.weixin.qq.com/connect/qrconnect?appid=wx3b76b88887d73db6&redirect_uri=http://www.healthcollege.cn&response_type=code&scope=snsapi_login&state=3d6be0a4035d839573b04816624a415e#wechat_redirect" alt=""> -->
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
// import codes from "@/api/msm";
import { getToken, setToken } from '@/utils/auth'
import getcode from "@/api/weichat";
export default {
  name: "Login",
  data() {
    const validateUsername = (rule, value, callback) => {
      console.warn("aaa", value);
      if (!value) {
        return callback(new Error("用户名不能为空"));
      }
      setTimeout(() => {
        if (value === value) {
          callback();
        } else {
          callback(new Error("用户名输入错误"));
        }
      }, 1000);
    };
    const validatePassword = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("密码不能为空"));
      }
      setTimeout(() => {
        if (value === value) {
          callback();
          console.warn("qqq", value);
        } else {
          callback(new Error("密码输入错误"));
        }
      }, 1000);
    };

    return {
      qrcodes: "",
      key: "",
      isActive: true, // 用于实现切换登录，作为判断
      isActiveIndex: 0,
      loginForm: {
        username: "",
        password: "",
      },
      loginForm2: {},
      loginRules: {
        username: [{required: true, validator: validateUsername, trigger: "blur" }],
        password: [{ required: true,validator: validatePassword, trigger: "blur" }],
      },
      token:'',
      loading: false,
      passwordType: "password",
      redirect: undefined,
    };
  },
  //页面加载调用获取cookie值
  mounted() {
    // this.getCookie();
    //初始化微信js

    const script = document.createElement("script");
    script.type = "text/javascript";
    // script.src ="https://res.wx.qq.com/connect/zh_CN/htmledition/js/wxLogin.js";
    script.src = require("../weichat");

    document.body.appendChild(script);
    this.token = this.$route.query.token;
    // setToken(this.token)
    // console.log('asdasd',this.token);
    // window.localStorage.setItem('token', this.token);
    // console.log('aaaaaaa',window.localStorage.getItem('token'));
  },
  watch: {
    $route: {
      handler: function (route) {
        this.redirect = route.query && route.query.redirect;
      },
      immediate: true,
    },
  },
  methods: {
    //微信回调方法


    weixinLogin() {
      const that = this;
      getcode.getQRcode().then((res) => {

        var href =
          "data:text/css;base64,I3dlaXhpbnsKICAgIC8qIGJhY2tncm91bmQtY29sb3I6ICNmY2Y7ICovCiAgICBkaXNwbGF5OiBmbGV4OwogICAganVzdGlmeS1jb250ZW50OiBjZW50ZXI7CiAgICBtYXJnaW4tdG9wOiAtMjBweDsKfQoud3JhcF9jb2Rle21hcmdpbi1sZWZ0OjIwcHh9Ci5pbXBvd2VyQm94e21hcmdpbi1sZWZ0OjIwcHgsZGlzcGxheTpmbGV4fQouaW1wb3dlckJveCAucXJjb2Rle3dpZHRoOjI1MHB4O2hlaWdodDoyNTBweH0KLmltcG93ZXJCb3ggLnRpdGxle2Rpc3BsYXk6bm9uZX0KLnN0YXR1c19pY29ue2Rpc3BsYXk6bm9uZX0=";
        var redirect_uri = decodeURIComponent(res.data.map.redirect_uri)
        console.log('tttttttt',decodeURIComponent(res.data.map.redirect_uri));

        var obj = new WxLogin({
          self_redirect: false,
          id: "weixinLogin", // 需要显示的容器id
          appid: res.data.map.appid, // 公众号appid wx*******
          scope: res.data.map.scope, // 网页默认即可
          // redirect_uri:res.data.map.redirect_uri,
          redirect_uri:redirect_uri,// 授权成功后回调的url
          state: res.data.map.state, // 可设置为简单的随机数加session用来校验
          style: "black", // 提供"black"、"white"可选。二维码的样式
          href: href, // 外部css文件url，需要https

        });
        // setToken(this.token)
        // this.$message.success("登录成功");
      // if(this.token){
      //   this.$router.push({
      //     path: this.redirect || "/",
      //   })
      // }
        // console.log('zsjzsjzsjnb',this.token);

      });
    },
    clearValidate(formName) {
      this.$refs[formName].clearValidate();
    },
    showPwd() {
      if (this.passwordType === "password") {
        this.passwordType = "";
      } else {
        this.passwordType = "password";
      }
    },
    accountLogin() {
      // 账号登录
      this.isActive = true;
      this.isActiveIndex = 0;
      this.loginForm2 = {};
      this.clearValidate("loginForm2");
    },
    handleLogin() {
      //window.localStorage.removeItem('key'); //清除文件
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          this.loading = true;
          this.$store
            .dispatch("user/login", this.loginForm)
            .then((resp) => {
              this.$router.push({
                path: this.redirect || "/",
                // query: this.otherQuery,
              });
              this.$message({
                message: "登录成功!",
                type: "success",
              });
              this.loading = false;
              // window.sessionStorage.setItem("userInfo",resp.data.token)
              // console.log('zsj',window.sessionStorage.setItem("userInfo",resp.data.token));
              // console.log(
              //   "123123123123",
              //   window.sessionStorage.setItem("userinfo",resp.data.token)
              // );
            })
            .catch(() => {
              this.loading = false;
              this.$message({
                message: "用户名或密码填写错误!",
                type: "error",
              });
            });
        } else {
        }
      });
    },

    smsLogin() {
      // 微信登录
      this.isActive = false;
      this.isActiveIndex = 1;
      this.weixinLogin();
      this.clearValidate("loginForm");
      console.log('123',this.token);

      // setToken(this.token)
      // if(this.token){
      //   this.$router.push({
      //     path: this.redirect || "/",
      //   })
      // }
    },
  },
  // created(){
  //   if(this.$route.query.token) {
  //     setToken(this.$route.query.token)
  //      this.$router.push({
  //         path: this.redirect || "/",
  //       })
      
  //     // this.$router.push("/login/loginwait");
  //     console.log('1231');
  //   }

  // }
};

</script>

<style scoped>
.mains {
  background: url(~@/assets/login3.jpg);
  /* background: url(~@/assets/login2.jpg); */
  /* background: url(../../../public/login.jpg); */
  background-size: 100% 100%;
  position: relative;
  opacity: .9;
}
.login_box {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%,-60%);
  width: 450px;
  height: 450px;
  background-color: hsla(0,0%,100%,.8);
  border-radius: 18px;
  padding: 30px 30px 30px 30px;
  box-shadow: 0 5px 10px hsla(0,0%,80%,.8);
}
.login_title {
  text-align: center;
  margin: 15px 30px 40px 30px;
  font-size: 22px;
  color: #666;
  
}
.login-logo{
  text-align: center;
    margin-top: 30px;
    font-size: 28px;
    color: #5DA58A;
    
}
.login_title span {
  margin: 0 20px 0 20px;
  cursor: pointer;
  
}
.login_title span:hover {
  color: #333;
  font-weight: bolder;
}
.isActiveTitle {
  color: #333;
  font-weight: bolder;
}
.login_agree {
  margin-left: 30px;
}
.login_btn {
  width: 100%;
  height: 50px;
  margin: 15px 0 0 10px;
  background-color: #409eff;
    border-color: #409eff;
    color: #fff;
}
.show-pwd {
  position: absolute;
  right: 10px;
  top: 5px;
  font-size: 16px;
  cursor: pointer;
  user-select: none;
}
.qrcode {
  width: 200px;
  height: 200px;
  border: 1px solid aqua;
  margin-left: 100px;
}
.tips {
  font-size: 15px;
  margin-top: 40px;
  margin-left: 100px;
}
.bottom {
  margin-left: 45px;
  margin-top: 10px;
}
#weixinLogin {
  /* background-color: #fcf; */
  display: flex;
  justify-content: center;
  margin-top: -40px;
}
</style>


